import { queryParkinglotNames } from '@/pages/Parking/Spot/service';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/types.d';
import {
  ModalForm,
  ProFormDigit,
  ProFormGroup,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-components';
import { message } from 'antd';
import { useModel } from 'umi';
import { updateMemberCard } from '../service';
import type { MemberCardModalForm, MemberCardTableItem, MemberCardTypeInfo } from '../types.d';
import { specialCharReg } from '@/utils/utils';
import { VehicleTypeEnum } from '@/pages/Parking/Records/types.d';
import { useState } from 'react';
import { MemberCardType } from '../../MemberRecord/types.d';

export default (props: { reload: () => void; memberCard: MemberCardTableItem }) => {
  const { initialState } = useModel('@@initialState');
  const { memberCard } = props;
  const userRole = initialState?.currentUser?.role;
  const { ownerId, cardNo, ownerInfo, parkingLots, cardName, vehicleType, allParkValid, typeInfo } =
    memberCard;
  const [allValid, setAllValid] = useState<boolean>(allParkValid || false);

  return (
    <ModalForm<MemberCardModalForm>
      title="修改模板卡"
      width="45vw"
      layout="horizontal"
      modalProps={{
        destroyOnClose: true,
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={<a>编辑</a>}
      initialValues={{
        cardName,
        vehicleType,
        // price: price / 100,
        parkingLotIds: parkingLots?.map((item) => item.parkingLotId),
        ownerId: ownerId,
        // type: type,
        [MemberCardType.YEAR]: typeInfo?.year
          ? {
              price: typeInfo?.year?.price / 100,
            }
          : undefined,
        [MemberCardType.SEASON]: typeInfo?.season
          ? {
              price: typeInfo?.season?.price / 100,
            }
          : undefined,
        [MemberCardType.MONTH]: typeInfo?.month
          ? {
              price: typeInfo?.month?.price / 100,
            }
          : undefined,
        allParkValid: allParkValid || false,
      }}
      onFinish={async (values) => {
        if (
          !values[MemberCardType.YEAR] &&
          !values[MemberCardType.SEASON] &&
          !values[MemberCardType.MONTH]
        ) {
          message.error({ key: 'update_card', content: '请至少填写一种会员卡类型' });
          return false;
        }
        const typeInfo: MemberCardTypeInfo = {};
        if (values[MemberCardType.YEAR]) {
          typeInfo[MemberCardType.YEAR] = {
            price: (values[MemberCardType.YEAR].price || 0) * 100,
            days: 365,
          };
        }
        if (values[MemberCardType.SEASON]) {
          typeInfo[MemberCardType.SEASON] = {
            price: (values[MemberCardType.SEASON].price || 0) * 100,
            days: 90,
          };
        }
        if (values[MemberCardType.MONTH]) {
          typeInfo[MemberCardType.MONTH] = {
            price: (values[MemberCardType.MONTH].price || 0) * 100,
            days: 30,
          };
        }
        const res = await updateMemberCard(cardNo, {
          ownerId: values.ownerId || ownerId,
          // price: (values.price || 0) * 100,
          parkingLotIds: values.allParkValid ? [] : values.parkingLotIds,
          // type: values.type,

          cardName: values.cardName,
          vehicleType: values.vehicleType,
          allParkValid: values.allParkValid,
          typeInfo,
        });
        if (res.success) {
          message.success({ key: 'update_card', content: res.message });
          props.reload();
          return true;
        }
        message.error({ key: 'update_card', content: res.message });
        return false;
      }}
    >
      <ProFormText
        name="cardName"
        label="模板卡名"
        rules={[
          {
            required: true,
            validator: (_, val) => {
              if (!val || specialCharReg.test(val))
                return Promise.reject(new Error('名称不符合规范，不支持包含特殊字符'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormSwitch
        name="allParkValid"
        label="全路通用"
        placeholder="是否适用于全路段"
        required
        fieldProps={{
          onChange: (val) => {
            setAllValid(val);
          },
        }}
      />
      {!allValid && (
        <ProFormSelect
          name="parkingLotIds"
          label="选择路段"
          showSearch
          mode="multiple"
          debounceTime={300}
          placeholder="请选择路段"
          rules={[{ required: true, message: '请选择路段' }]}
          request={(val) => queryParkinglotNames(val.keyWords)}
        />
      )}
      <ProFormSelect
        name="vehicleType"
        label="适用车辆"
        mode="multiple"
        required
        placeholder="请选择适用车辆类型"
        options={[
          {
            label: '普通小型车',
            value: VehicleTypeEnum.COMMON_SMALL,
          },
          {
            label: '普通大型车',
            value: VehicleTypeEnum.COMMON_LARGE,
          },
          {
            label: '新能源小型车',
            value: VehicleTypeEnum.NEW_ENERGY_SMALL,
          },
          {
            label: '新能源大型车',
            value: VehicleTypeEnum.NEW_ENERGY_LARGE,
          },
          {
            label: '警车',
            value: VehicleTypeEnum.POLICE,
          },
          {
            label: '武警',
            value: VehicleTypeEnum.ARMED,
          },
        ]}
      />
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="归属公司"
          showSearch
          debounceTime={300}
          placeholder="请选择归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords || ownerInfo?.ownerName)}
        />
      )}
      <ProFormGroup
        style={{
          marginLeft: '60px',
        }}
        title="会员卡类型"
        tooltip="若不填写价格，则默认为不可办理当前类型； 不可全部为空"
      >
        <ProFormDigit
          label="包月价格"
          width="md"
          addonAfter="元"
          name={[MemberCardType.MONTH, 'price']}
          placeholder="请输入包月会员（30天）的价格"
          fieldProps={{
            precision: 2,
          }}
          min={0}
        />
        <ProFormDigit
          label="包季价格"
          width="md"
          addonAfter="元"
          name={[MemberCardType.SEASON, 'price']}
          placeholder="请输入包季会员（90天）的价格"
          fieldProps={{
            precision: 2,
          }}
          min={0}
        />
        <ProFormDigit
          label="包年价格"
          width="md"
          addonAfter="元"
          name={[MemberCardType.YEAR, 'price']}
          placeholder="请输入包年会员（365天）的价格"
          fieldProps={{
            precision: 2,
          }}
          min={0}
        />
      </ProFormGroup>
    </ModalForm>
  );
};
